var grid = "";
var validator = "";
var allowSave = true;
var hideColumn = function(column) {
	if ((editingParams.enrollment && editingParams.performance) || (editingParams.hasPBSScholarshipType && editingParams.hasNonPBSScholarshipType)) {
		return true;
	} else if (column == "enrollment_units") {
		return editingParams.performance || editingParams.hasNonPBSScholarshipType;
	} else if (column == "enrollment_attendance_level") {
		return editingParams.performance || editingParams.hasPBSScholarshipType;	
	} else if (column == "enrollment_degree_level") {
		return editingParams.performance;		
	} else if (column == "performance_credits") {
		return editingParams.enrollment;
	} else if (column == "performance_gpa") {
		return editingParams.enrollment;	
	}
	return false;
};
var payment = kendo.data.Model.define({
	id: "payment_id",
	fields: {
		// uneditable fields
		payment_id: {type: "number", editable: false, nullable: true},
		scholarship_id: {type: "number", editable: false, nullable: true},
		payment_schedule_id: {type: "number", editable: false, nullable: true},
		opt_out: {type: "boolean", editable: true, nullable: true},
		opt_out_reason: {type: "string", editable: true, nullable: true},
		institution1_id: {type: "number", editable: false, nullable: true},
		// editable cells
		institution1_document_date: {type: "date", editable: true, nullable: true},
		institution1_enrollment_units: {type: "number", editable: true, nullable: true},
		institution1_enrollment_attendance_level: {type: "string", editable: true, nullable: true},
		institution1_enrollment_degree_level: {type: "string", editable: true, nullable: true},
		institution1_performance_credits: {type: "number", editable: true, nullable: true},
		institution1_performance_gpa: {type: "number", editable: true, nullable: true},
		/*
		institution2_id: {type: "number", editable: false, nullable: true},
		institution2_document_date: {type: "date", editable: true, nullable: true},
		institution2_enrollment_units: {type: "number", editable: true, nullable: true},
		institution2_enrollment_attendance_level: {type: "string", editable: true, nullable: true},
		institution2_enrollment_degree_level: {type: "string", editable: true, nullable: true},
		institution2_performance_credits: {type: "number", editable: true, nullable: true},
		institution2_performance_gpa: {type: "number", editable: true, nullable: true},
		institution3_id: {type: "number", editable: false, nullable: true},
		institution3_document_date: {type: "date", editable: true, nullable: true},
		institution3_enrollment_units: {type: "number", editable: true, nullable: true},
		institution3_enrollment_attendance_level: {type: "string", editable: true, nullable: true},
		institution3_enrollment_degree_level: {type: "string", editable: true, nullable: true},
		institution3_performance_credits: {type: "number", editable: true, nullable: true},
		institution3_performance_gpa: {type: "number", editable: true, nullable: true},
		*/
		approval_date: {type: "date", editable: true, nullable: true},
		payment_submitted_date: {type: "date", editable: true, nullable: true},
		payment_date: {type: "date", editable: true, nullable: true},
		payment_type: {type: "string", editable: true, nullable: true},
		payment_amount: {type: "number", editable: true, nullable: true},
		payment_reference: {type: "string", editable: true, nullable: true},
		notes: {type: "string", editable: true, nullable: true},
		date_created: {type: "date", editable: false, nullable: true},
		// non-payment properties
		// scholarship
		claim_id: {type: "string", editable: false, nullable: true},
		first_name: { type: "string", editable: false, nullable: true},
		last_name: {type: "string", editable: false, nullable: true},
		full_name: {type: "string", editable: false, nullable: true},
		authorized: {type: "boolean", editable: false, nullable: true},
		// payment_schedule
		cohort: {type: "number", editable: false, nullable: true},
		scholarship_type: {type: "string", editable: false, nullable: true},
		term: {type: "string", editable: false, nullable: true},
		term_type: {type: "string", editable: false, nullable: true},
		verification_type: {type: "string", editable: false, nullable: true}
		// institution1
		
		// institution2
	}
});
var customPaymentsGridValidator = {
	/*
	institution1_enrollment_units
	institution1_performance_credits
	institution1_performance_gpa
	*/
	/*------------------------------ 
			
	not sure about allowSave switch throughout the code below
	
	------------------------------*/
	rules: {
		date: function(input) {
			// dates must be blank or a valid date
			if (input[0].value.length > 0) {
				var inputNameArray = input[0].name.split("_");
				if (inputNameArray[inputNameArray.length - 1] == "date") {
					if (!isValidDate(input[0].value)) {
						allowSave = false;
						return false;
					}
				}
			}
			allowSave = true;
			return true;
		},
		number: function(input) {
			// all number fields must be null or a number gt 0
			if (input[0].value > 0) {
				var inputNameArray = input[0].name.split("_");
				var lastNamePart = inputNameArray[inputNameArray.length - 1];
				if (lastNamePart == "units" || lastNamePart == "credits" || lastNamePart == "gpa" || lastNamePart == "amount") {
					if (!$.isNumeric(input[0].value) || input[0].value < 0) {
						allowSave = false;
						return false;
					}
				}
			}
			allowSave = true;
			return true;
		}
	},
	messages: {
		date: "Invalid date",
		number: "Invalid number"	
	}
};
var payments = new kendo.data.DataSource({
	autoSync: false,
	transport: {
		read: {url: "/assets/calgrants/com/API.cfc", dataType: "json", type: "GET", cache: false},
		create: {url: "/assets/calgrants/com/API.cfc", dataType: "json", type: "POST"},
		update: {url: "/assets/calgrants/com/API.cfc", dataType: "json", type: "POST", complete: function(jqXHR, textStatus) {console.log("transport update completed")}},
		destroy: {url: "/assets/calgrants/com/API.cfc", dataType: "json", type: "POST"},
		parameterMap: function(params, transportType) {
			params.objType = "payment";
			params.method = transportType;
			if (params.method == "read") {
				$.extend(params, queryParams);
			} else {
				$.extend(params, params.models[0]);
				params.models = "";
			}
			return params;
		}	
	},
	schema: {
		type: "json",
		model: payment
	},
	batch: true,
	serverPaging: false,
	page: 1,
	pageSize: 20,
	serverSorting: false,
	sync: function(e) {
		console.log("sync completed");// do nada for now
	}
});
var datePicker = function(container, options) {
	var dp = $("<input/>");
	dp.attr("name", options.field); 
	//input.attr("disabled", "disabled");
	dp.appendTo(container);
	dp.kendoDatePicker({
		//change: function() {console.log("datePicker changed to:"); console.log(this)},
		//close: function() {console.log("datePicker closed with:"); console.log(this)},
		//opened: function() {console.log("datePicker opened while while:"); console.log(this)}
	});
}
var rowButtonsTemplate = 		'<a id="editLink_#=uid#" href="" onclick="editRow(\'#=uid#\'); return false;" class="btn btn-mini btn-primary" style="width: 35px;">Edit</a> ' +
								'<a id="deleteLink_#=uid#" href="" onclick="deleteRow(\'#=uid#\'); return false;" class="btn btn-mini btn-primary" style="width: 35px;">Delete</a>' +
								'<a id="saveLink_#=uid#" href="" onclick="saveRow(\'#=uid#\'); return false;" class="btn btn-mini btn-primary" style="display: none; width: 35px;">Save</a> ' +
								'<a id="cancelLink_#=uid#" href="" onclick="cancelRow(\'#=uid#\'); return false;" class="btn btn-mini btn-primary" style="display: none; width: 35px;">Cancel</a>';
var editRow = function(uid) {
	var row = $("#paymentsGrid tr[data-uid='" + uid + "']");
	toggleButtons(uid, "edit");
	grid.editRow(row);
	return true;
};
var deleteRow = function(uid) {
	if (confirm("Are you sure you want to delete this record?")) {
		var row = $("#paymentsGrid tr[data-uid='" + uid + "']");
		grid.removeRow(row);
		//toggleButtons(uid, "delete");
		return true;
	} else {
		return false;
	}
};
var saveRow = function(uid) {
	if (allowSave) {
		var row = $("#paymentsGrid tr[data-uid='" + uid + "']");
		grid.saveRow(row);
		toggleButtons(uid, "save");
		return true;
	} else {
		alert("Cannot save with invalid data");
		return false;
	}
};
var cancelRow = function(uid) {
	var row = $("#paymentsGrid tr[data-uid='" + uid + "']");
	grid.cancelRow(row);
	toggleButtons(uid, "cancel");
	return true;
};
var toggleButtons = function(uid, mode) {
	var editButton = $("a[id='editLink_" + uid + "']");
	var deleteButton = $("a[id='deleteLink_" + uid + "']");
	var saveButton = $("a[id='saveLink_" + uid + "']");
	var cancelButton = $("a[id='cancelLink_" + uid + "']");
	if (mode == "edit") {
		editButton.hide();
		deleteButton.hide();
		saveButton.show();
		cancelButton.show();
	} else if (mode == "save") {
		editButton.show();
		deleteButton.show();
		saveButton.hide();
		cancelButton.hide();
	} else if (mode == "cancel") {
		editButton.show();
		deleteButton.show();
		saveButton.hide();
		cancelButton.hide();
	}
}
var disableSaveButton = function() {
	
}
var createGrid = function(){
	grid = $("#paymentsGrid").kendoGrid({
		dataSource: payments,
		autoBind: true,
		columns: [
			{field: "payment_id", title: "ID", template: "<a href='?view=editPayment&Payment_ID=#=payment_id#'>#=payment_id#</a>", menu: false},
			{field: "cohort", title: "Cohort"},
			{field: "claim_id", title: "Claim ID"},
			{field: "full_name", title: "Name"},
			//{title: "Name", template: "#=first_name# #=last_name#"},
			{field: "scholarship_type", title: "Scholarship Type"},
			{field: "term", title: "Term"},
			{field: "term_type", title: "Term Type"},
			{field: "verification_type", title: "Verification Type"},
			//{field: "opt_out", title: "No payment", width: 120},
			{field: "institution1_document_date", title: "Verification Date", format: "{0:M/d/yyyy}", filterable: {ui: "datepicker"}},
			//format for integer, select box
			{field: "institution1_enrollment_units", title: "Units", format: "{0:0.00}", hidden: hideColumn("enrollment_units")},
			{field: "institution1_enrollment_attendance_level", title: "Attendance", values: attendanceLevels, hidden: hideColumn("enrollment_attendance_level")},
			{field: "institution1_enrollment_degree_level", title: "Degree", values: degreeLevels, hidden: hideColumn("enrollment_degree_level")},
			{field: "institution1_performance_credits", title: "Credits", format: "{0:0.00}", hidden: hideColumn("performance_credits")},
			{field: "institution1_performance_gpa", title: "GPA", format: "{0:0.000}", hidden: hideColumn("performance_gpa")},
			{field: "approval_date", title: "Approval Date", format: "{0:M/d/yyyy}", filterable: {ui: "datepicker"}},
			{field: "payment_date", title: "Payment Date", format: "{0:M/d/yyyy}", filterable: {ui: "datepicker"}},
			{field: "payment_amount", title: "Payment Amount", format: "{0:c}"},
			{title: "", template: rowButtonsTemplate, attributes: {nowrap: "nowrap"}, hidden: hideColumn("commands")}
		],
		editable: {
			confirmation: "Are you sure you want to delete the selected record?",
			createAt: "top",
			update: true,
			destroy: true,
			mode: "inline"
		},
		sortable: true,
		filterable: {
			extra: true,
			messages: {
				and: "and",
				or: "or",
				filter: "Apply",
				clear: "Clear",
				info: "Column filter",
				isFalse: "Is false",
				isTrue: "Is true",
				selectValue: "Select..."
			},
			operators: {
				string: {
					eq: "Equals",
					neq: "Does not equal",
					contains: "Contains",
					doesnotcontain: "Does not contain",
					startswith: "Starts with",
					endswith: "Ends with"
				},
				date: {
					eq: "On",
					neq: "Not on",
					gte: "On or after",
					gt: "After",
					lte: "On or before",
					lt: "Before"
				},
				number: {
					eq: "Equal",
					neq: "Not equal",
					gte: "Greater than or equal",
					gt: "Greater than",
					lte: "Less than or equal",
					lt: "Less than"
				}
			}
		},
		groupable: {
			messages: {
				empty: "Drop column here to group"		
			}
		},
		columnMenu: true,
		/*columnMenu: {
			columns: true,
			filterable: true,
			sortable: false,
			messages: {
				columns: "Columns ",
				filter: "Filter ",
				sortAscending: "Sort A -> Z ",
				sortDescending: "Sort Z -> A "	
			}
		},*/
		reorderable: true,
		resizable: true,
		pageable: {
			pageSize: 20,
			pageSizes: [20, 50, 100, 200, 500],
			buttonCount: 20,
			input: true,
			info: true,
			messages: {
				display: "{0} - {1} of {2} records",
				empty: "Loading...",
				itemsPerPage: "records per page"
			}
		}	
	}).data("kendoGrid");
	
	validator = kendo.ui.validator;
	$.extend(true, validator, customPaymentsGridValidator);
};